package com.yoipdu.im1.controller;

import com.yoipdu.im1.entity.Content;
import com.yoipdu.im1.service.UserService;
import com.yoipdu.im1.service.WebSocketService;
import com.yoipdu.im1.service.impl.UserServiceImpl;
import com.yoipdu.im1.util.JsonData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

@CrossOrigin
@RestController
public class UserController {
    private UserService service;
    private WebSocketService webSocketService;
    private JsonData json;

    @Autowired
    public void setService(UserServiceImpl service) {
        this.service = service;
    }

    @Autowired
    public void setWebSocketService(WebSocketService service) {
        this.webSocketService = service;
    }

    @PostMapping("/login")
    public Map<String, Object> login() {
        json = new JsonData();
        json.setContent(service.login());
        json.put("number", webSocketService.getSize() + 1);
        webSocketService.sendAllMessage(webSocketService.getSize() + 1);
        return json.to();
    }

    @PostMapping("/send")
    public Map<String, Object> send(@RequestBody Content content) {
        json = new JsonData();
        webSocketService.sendAllMessage(content);
        return json.to();
    }
}
